<?php
	class ProfileController extends Controller
	{
		public function actionProfile()
		{
			$setl = Settlements::model()->findByPk(User::model()->findByPk(Yii::app()->user->getId())->current_settlement);
			$user = User::model()->findByPk(Yii::app()->user->getId());
			$this->render('profile', array('settlement' => $setl, 'user' => $user));
		}
		
		public function actionChangeName()
		{
			$model = Settlements::model()->findByPk(
													User::model()->findByPk(
																			Yii::app()->user->getId()
																			)->current_settlement
													);
			
			$model->name = $_POST['Settlements']['name'];
			if(!$model->validate())
			{
				Yii::app()->user->setFlash('error', 'Длина названия деревни от 3 символов');
				$this->redirect($this->createUrl('profile/profile'));
			}
			
			$model->save();
			
			$this->redirect($this->createUrl('field/fields'));
		}
		
		public function actionChangePassword()
		{
			$model = User::model()->findByPk(Yii::app()->user->getId());
			
			if($model->password != md5($_POST['User']['old_password']))
			{
				Yii::app()->user->setFlash('error', 'Старый пароль неверен');
				$this->redirect($this->createUrl('profile/profile'));
			}
			
			if($_POST['User']['new_password'] != $_POST['User']['re_new_password'])
			{
				Yii::app()->user->setFlash('error', 'Новый пароль неверно повторен');
				$this->redirect($this->createUrl('profile/profile'));
			}
			
			if(strlen($_POST['User']['new_password']) < 3)
			{
				Yii::app()->user->setFlash('error', 'Новый пароль от 3 символов');
				$this->redirect($this->createUrl('profile/profile'));
			}
			
			$model->updateAll(array('password' => md5($_POST['User']['new_password'])));
			
			$this->redirect($this->createUrl('auth/logout'));
		}
		
		public function actionChangeSettlement()
		{
			$id = $_GET['id'];
			
			$user = User::model()->findByPk(Yii::app()->user->getId());
			$user->current_settlement = $id;
			$user->update();
			
			$this->redirect($this->createUrl('field/fields'));
		}
	}
?>